package com.foocus.foocuscloud.common.exception;

import com.foocus.foocuscloud.common.domain.ResponseWrapper;
import com.foocus.foocuscloud.common.tips.TipMess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandle {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResponseWrapper exceptionHandle(Throwable e) {
        LOGGER.error("异常信息：{}", e);
        return ResponseWrapper.Fail(TipMess.SYSTEM_INTERNAL_ERROR);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseWrapper exceptionHandle(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        LOGGER.error("异常请求：{}, 异常信息：{}", requestURI, e);
        e.printStackTrace();
        return ResponseWrapper.Fail(TipMess.SYSTEM_INTERNAL_ERROR);
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseWrapper exceptionHandle(BusinessException e) {

        LOGGER.error("Handle BusinessException: {}", e);
        return ResponseWrapper.Fail(e.getMessage());
    }
}
